
<template>
  <div>
    <div class="main w">
      <div class="mainTitle">
        <span>
          机关教辅单位服务作风评价 -
          <i class="voting">集中评价</i>
        </span>
      </div>
      <div class="left">
        <div class="leftTitle">
          <span>评价项目</span>
        </div>
        <div class="leftContent">
          <span
            class="subject"
          >{{index == departmentAllList.length ? departmentAllList.length : (index+1) }}.{{departmentList.title}}</span>
          <ul>
            <li v-html="departmentList.detail "></li>
          </ul>
        </div>
      </div>
      <div class="right">
        <div id="target" class="rightTop">
          <span>机关教辅单位</span>
        </div>
        <form>
          <div class="vote">
            <ul>
              <!--遍历部门名称 -->
              <li
                class="bumen"
                v-for="(item,index) in departmentList.departmentQuestionnaireDtoList"
                :key="item.depid"
              >
                <span class="unitName">{{index+1}} . {{item.name}}</span>
                <div class="selectBox">
                  <ul class="ansBox">
                    <li
                      v-show="departmentList.typeId == 1 ? true : false"
                      class="ansInput"
                      v-for="(items,i) in item.answers"
                      :key="i.id"
                    >
                      <input
                        class="radioClass"
                        type="radio"
                        :name="item.name"
                        :id="item.depid"
                        :value="departmentList.questionnaireId +'/' + item.depid + '/'+items.answerDesc + '/' + items.id"
                        v-model="requiredItems[index]"
                      >
                      <span>{{items.answerDesc}}</span>
                    </li>
                  </ul>
                  <!-- 判断第4题 -->
                  <textarea
                    v-if="departmentList.typeId == 2 && departmentList.questionnaireId == 4 ? true : false"
                    class="txtArea"
                    name="txt"
                    warp="virtual"
                    placeholder="请输入打交道次数"
                    maxlength="4"
                    v-model="textAreaList[index]"
                    @input="descArea"
                    :data-text=" requiredItems[index] = departmentList.questionnaireId +'/' + item.depid + '/'+ textAreaList[index] "
                  ></textarea>
                  <!-- 判断简答题 -->
                  <textarea
                    v-if="departmentList.typeId == 2 && departmentList.questionnaireId != 4 "
                    class="txtArea"
                    name="txt"
                    warp="virtual"
                    placeholder
                    maxlength="800"
                    @change="blankDescArea"
                    v-model="textAreaList[index]"
                    :data-text=" requiredItems[index] = departmentList.questionnaireId +'/' + item.depid + '/'+ textAreaList[index] "
                  ></textarea>
                </div>
              </li>
            </ul>
          </div>

          <div class="buttonBox">
            <!-- 判断页面id的显示上下翻页 -->
            <div v-if="index > 0 ? true : false" class="btn backBtn" @click="backPage">上一项</div>
            <div
              v-if="index < departmentAllList.length - 1 ? true : false"
              id="to-top-btn"
              class="btn nextBtn"
              @click="nextPage"
            >下一项</div>
            <div
              v-if="index == departmentAllList.length - 1 ? true : false"
              class="btn nextBtn"
              @click="nextPage"
            >提交</div>
          </div>
        </form>
      </div>
    </div>
  </div>
</template>
<style>
/* alert提示框样式 */
.user-defined-style {
  top: 45%;
}
</style>

<script>
export default {
  name: "departentPage",
  data() {
    return {
      departmentList: {}, //当前题的信息
      requiredItems: [],//选择题的内容
      requiredItemsR: [],//保存选择题的容器
      textAreaList: [], //保存文本域内容，但不包括Id,
      textAreaListR: [], //保存文本输入框的容器
      answerDesc: "",
      index: 0, //默认取第一个
      departmentAllList: [], //全部的数据
      evaluateSubmit: [], //提交的数据
      isSubmit: false //是否提交 , 关闭弹窗提示
    };
  },
  created() {
    this.getDepartmentList();
  },
 
  methods: {
    //校验输入是否为数字
    descArea() {
      var textVal = this.textAreaList;
      textVal.forEach((j, idx) => {
        var answersStr = j.split("/")[0];
        let val = Number(answersStr);
        // console.log("123", val);
        if (isNaN(val)) {
          //判断是不是数字
          this.$message({
            showClose: false,
            message: "仅支持 0-9 的阿拉伯数字格式哦!",
            type: "error",
            center: true, //文字居中
            customClass: "user-defined-style",
            duration: 1500
          });
          this.textAreaList[idx] = "";
          return;
        }
      });
    },
    //校验输入是否为空格
    blankDescArea() {
      var textVal = this.textAreaList;
      // console.log("jj", textVal);
      textVal.forEach((j, idx) => {
        var answersStr = j.split("/")[0];
        // console.log("idx",idx);
        if (answersStr.match(/^\s*$/)) {
          this.$message({
            showClose: false,
            message: "第" + (idx + 1) + "个部门不能为空!!",
            type: "error",
            center: true, //文字居中
            customClass: "user-defined-style",
            duration: 1500
          });
          this.textAreaList[idx] = "";
          return;
        }
      });
    },
    getDepartmentList() {
      this.axios.get("api/department/edit").then(response => {
        this.departmentAllList = response.data.data; //改了 所有题
        this.departmentList = this.departmentAllList[this.index]; //改了 当前题index
        // console.log("timu", this.departmentList);
      });
    },
    //返回上一页
    backPage() {
      if (this.index == this.departmentAllList.length - 1) {
        //最后一页返回上页，保存数据
        var arr = this.requiredItems;
        this.requiredItemsR[this.index] = arr;
        this.textAreaListR[this.index] = this.textAreaList;
      }
      this.index--;
      //显示原评价内容
      this.requiredItems = this.requiredItemsR[this.index]; //提取保存的评价内容
      this.textAreaList = this.textAreaListR[this.index]; //提取保存的评论内容
      this.departmentList = this.departmentAllList[this.index];
    },
    //点击下一页时让页面返回顶部
    backTop() {
      document.body.scrollTop = 0;
      document.documentElement.scrollTop = 0;
    },
    // 前往下一页逻辑 index ++
    nextPageSize() {
      this.index++;
      this.requiredItems = [];
      this.textAreaList = [];
      var currentR = this.requiredItemsR[this.index];
      //当前页之前是否已被评价
      if (currentR != undefined && currentR.length > 0) {
        //评价过，显示原有数据
        this.requiredItems = currentR;
        this.textAreaList = this.textAreaListR[this.index];
      }
      this.departmentList = this.departmentAllList[this.index]; //改了
    },
    //弹窗提示是否进入下一页
    nextMessageBox() {
      if (this.index == this.departmentAllList.length - 1) {
        this.$confirm("检测到当前还有项目未填写完毕，是否确定提交?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            this.submit(); // 提交!
          })
          .catch(() => {});
      } else {
        this.$confirm(
          "检测到当前还有项目未填写完毕，是否确定进入下一项?",
          "提示",
          {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning"
          }
        )
          .then(() => {
            this.nextPageSize(); // 进入下一页!
          })
          .catch(() => {});
      }
    },
    //弹窗提示未填完 ,必须填完才能进入下一页
    overMessageBox() {
      if (this.index == this.departmentAllList.length - 1) {
        this.$alert("还有项目未填写完毕，请填写完毕再提交!!", "提示", {
          confirmButtonText: "确定",
          type: "error"
        });
        return;
      } else {
        this.$alert("还有项目未填写完毕，请填写完毕再进入下一项!!", "提示", {
          confirmButtonText: "确定",
          type: "error"
        });
        return;
      }
    },
    //弹窗提示保存成功进入下一页
    saveSuccess() {
      if (this.index == this.departmentAllList.length - 1) {
        this.submit();
      } else {
        this.$message({
          showClose: false,
          message: "你的评价信息已经被保存!",
          type: "success",
          center: true, //文字居中
          customClass: "user-defined-style",
          duration: 600
        });
        this.nextPageSize(); // 进入下一页!
      }
    },
    // 进入下一页前先验证是否全部填完
    nextPage() {
      var arr = this.requiredItems; //保存已经评价的内容
      this.requiredItemsR[this.index] = arr;
      this.textAreaListR[this.index] = this.textAreaList;
      var departments = this.departmentList.departmentQuestionnaireDtoList; //部门数量

      if (this.departmentList.necessary == 0) {
        //必填题校验是否全部提交
        if (this.departmentList.typeId == 2) {
          //todo 当前页  以及当前页结果校验
          var b = arr.join("").split("undefined");
          // console.log("bbb", b, "arr", arr);

          //校验是否全部评价
          if (b.length > 1) {
            this.nextMessageBox(); //调用弹窗方法
          } else {
            this.saveSuccess(); //全部填完保存成功
            this.$options.methods.backTop(); //调用返回顶部的方法
          }
        } else if (this.departmentList.typeId == 1) {
          var b = arr.join("").split("/");
          //  console.log("bbb", b, "arr", arr);
          //  console.log("arrjoin", arr.join(""));
          // console.log("len",departments.length * 3 + 1);

          if (b.length < departments.length * 3 + 1) {
            this.nextMessageBox(); //调用弹窗方法
          } else {
            this.saveSuccess(); //全部填完保存成功
            this.$options.methods.backTop(); //调用返回顶部的方法
          }
        }
      } else if (this.departmentList.necessary == 1) {
        if (this.departmentList.typeId == 2) {
          //todo 当前页  以及当前页结果校验
          var b = arr.join("").split("undefined");
          //校验是否全部评价
          if (b.length > 1) {
            this.overMessageBox(); //调用弹窗方法
          } else {
            this.saveSuccess(); //全部填完保存成功
            this.$options.methods.backTop(); //调用返回顶部的方法
          }
        } else if (this.departmentList.typeId == 1) {
          var b = arr.join("").split("/");
          if (b.length < departments.length * 3 + 1) {
            this.overMessageBox(); //调用弹窗方法
          } else {
            this.saveSuccess(); //全部填完保存成功
            this.$options.methods.backTop(); //调用返回顶部的方法
          }
        }
      }
    },

    submit() {
      var arr = this.requiredItems;
      this.requiredItemsR[this.index++] = arr;
      this.textAreaListR[this.index] = this.textAreaList;
      // console.log("6666", this.index);

      for (var i = 0; i < this.index; i++) {
        // console.log("this.requiredItemsR[i]", this.requiredItemsR[i]);
        var requiredItems = this.requiredItemsR[i]; //容器
        requiredItems.forEach(j => {
          var answersArr = j.split("/");
          // console.log("kong", answersArr);
          // 判断如果textarea的值是undefined ,就删除
          if (answersArr[2] == "undefined") {
            answersArr.splice(2, 1);
            this.evaluateSubmit.push({
              questionnaireId: answersArr[0],
              evaluatedDepartmentId: answersArr[1],
              answerDesc: answersArr[2],
              answerId: answersArr[3]
            });
          } else {
            this.evaluateSubmit.push({
              questionnaireId: answersArr[0],
              evaluatedDepartmentId: answersArr[1],
              answerDesc: answersArr[2],
              answerId: answersArr[3]
            });
          }
        });
      }
      this.axios({
        url: "api/department/submit",
        method: "post",
        data: { answers: this.evaluateSubmit },
        headers: {
          "Content-Type": "application/json"
        }
      }).then(response => {
        this.evaluateSubmit = [];
        // console.log(response);
        this.isSubmit = true; //判断是否已经点击提交按钮,已提交改为true
        if (response.data.code == 0) {
          //成功
          this.$alert("你的评价提交成功!", "恭喜", {
            confirmButtonText: "确定",
            type: "success"
          }).then(() => {
            this.$router.push("/page/home");
          });
          return;
        } else {
          this.$alert(response.data.message, "错误", {
            confirmButtonText: "确定",
            type: "error"
          });
          // .then(() => {
          //   this.$router.push("/page/home");
          // });
          return;
        }
      });
    }
    
  },
  // 页面刷新提醒
  mounted() {
    window.onbeforeunload = function(e) {
      e = e || window.event;
      // 兼容IE8和Firefox 4之前的版本
      if (e) {
        e.returnValue = "您的评价结果未提交，是否确定提交后再离开？";
      }
      // Chrome, Safari, Firefox 4+, Opera 12+ , IE 9+
      return "您的评价结果未提交，是否确定提交后再离开？";
    };
  },
  //提示是否重新加载弹窗
  destroyed() {
    window.onbeforeunload = null;
  },
  //关闭弹窗提示
  beforeRouteLeave(to, from, next) {
    if (this.isSubmit == true) {
      //如果是true 侧放行不弹窗
      next();
    } else if (this.isSubmit == false) {
      next(false); //是false就弹窗
      this.$confirm("您的评价结果未提交，是否确定提交后再离开？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        // 选择确定
        next();
      });
    }
  }
};

</script>

